Grokking Google Coding Interview
Rate this course
Ask Author
Contribute
Back to course home

0% completed

Vote For New Content
Introduction
Who Should Take This Course?
Google Easy
Add Binary (easy)
Solution: Add Binary
Valid Mountain Array (easy)
Solution: Valid Mountain Array
Set Mismatch (easy)
Solution: Set Mismatch
Is Subsequence (easy)
Solution: Is Subsequence
Length of Last Word (easy)
Solution: Length of Last Word
Search Insert Position (easy)
Solution: Search Insert Position
Repeated Substring Pattern (easy)
Solution: Repeated Substring Pattern
Monotonic Array (easy)
Solution: Monotonic Array
Count Nodes Equal to Average of Subtree (easy)
Solution: Count Nodes Equal to Average of Subtree
Find the Difference (easy)
Solution: Find the Difference
How Many Numbers Are Smaller Than the Current Number (easy)
Solution: How Many Numbers Are Smaller Than the Current Number
Binary Tree Paths (easy)
Solution: Binary Tree Paths
Find the Difference of Two Arrays (easy)
Solution: Find the Difference of Two Arrays
Merge Strings Alternately (easy)
Solution: Merge Strings Alternately
Reverse a LinkedList (easy)
Solution: Reverse a LinkedList
Google Medium
Gray Code (medium)
Solution: Gray Code
2 Keys Keyboard (medium)
Solution: 2 Keys Keyboard
Arithmetic Slices (medium)
Solution: Arithmetic Slices
Unique Length-3 Palindromic Subsequences (medium)
Solution: Unique Length-3 Palindromic Subsequences
Minimum Difference Between Largest and Smallest Value in Three Moves (medium)
Solution: Minimum Difference Between Largest and Smallest Value in Three Moves
Letter Combinations of a Phone Number (medium)
Solution: Letter Combinations of a Phone Number
01 Matrix (medium)
Solution: 01 Matrix
Maximum Points You Can Obtain from Cards (medium)
Solution: Maximum Points You Can Obtain from Cards
Strobogrammatic Number II (medium)
Solution: Strobogrammatic Number II
Maximum Length of Semi-Decreasing Subarrays (medium)
Solution: Maximum Length of Semi-Decreasing Subarrays
Minimum Area Rectangle (medium)
Solution: Minimum Area Rectangle
Count Unreachable Pairs of Nodes in an Undirected Graph (medium)
Solution: Count Unreachable Pairs of Nodes in an Undirected Graph
Single Number II (medium)
Solution: Single Number II
4Sum II (medium)
Solution: 4Sum II
Furthest Building You Can Reach (medium)
Solution: Furthest Building You Can Reach
Minimizing Array After Replacing Pairs With Their Product (medium)
Solution: Minimizing Array After Replacing Pairs With Their Product
Fair Distribution of Cookies (medium)
Solution: Fair Distribution of Cookies
Find Leaves of Binary Tree (medium)
Solution: Find Leaves of Binary Tree
Rotate Image (medium)
Solution: Rotate Image
Combination Sum (medium)
Solution: Combination Sum
Implement Trie (Prefix Tree) (medium)
Solution: Implement Trie (Prefix Tree)
Number of Islands (medium)
Solution: Number of Islands
Edit Distance (medium)
Solution: Edit Distance
Container With Most Water (Medium)
Solution: Container With Most Water
Meeting Rooms II (medium)
Solution: Meeting Rooms II
Shortest Subarray with Sum at Least K (hard)
Solution: Shortest Subarray with Sum at Least K
Reverse Pairs (hard)
Solution: Reverse Pairs
Nth Magical Number (hard)
Solution: Nth Magical Number
Candy (hard)
Solution: Candy
Arithmetic Slices II - Subsequence (hard)
Solution: Arithmetic Slices II - Subsequence
Burst Balloons (hard)
Solution: Burst Balloons
Sum of Distances in Tree (hard)
Solution: Sum of Distances in Tree
Maximum Score of a Good Subarray (hard)
Solution: Maximum Score of a Good Subarray
Trapping Rain Water (hard)
Solution: Trapping Rain Water
First Missing Positive (hard)
Solution: First Missing Positive
Solution: Strobogrammatic Number II

Problem Statement

Given a positive integer n, return all the strobogrammatic numbers which are of length n. Return the answer in any order.

A strobogrammatic number is a number that looks the same when flipped upside down.

Examples

  • Example 1:

    • Input: n = 2
    • Expected Output: ["11", "69", "88", "96"]
    • Justification: When these numbers are rotated 180 degrees, they appear the same as their original form. Other two-digit combinations do not retain the same appearance after being flipped.
  • Example 2:

    • Input: n = 1
    • Expected Output: ["0", "1", "8"]
    • Justification: These are the only single-digit numbers that look the same when viewed upside down.
  • Example 3:

    • Input: n = 3
    • Expected Output: ["101", "609", "808", "906", "111", "619", "818", "916", "181", "689", "888", "986"]
    • Justification: These numbers are symmetrical and maintain their appearance when flipped 180 degrees. Other three-digit numbers do not meet this criterion.

Solution

To solve this problem, we start by recognizing that strobogrammatic numbers are formed by pairing certain digits: 0 with 0, 1 with 1, 8 with 8, 6 with 9, and 9 with 6. Our approach involves constructing these numbers from the middle outwards, ensuring symmetry and adherence to the strobogrammatic principle. For numbers of even length, we begin with an empty string and progressively add strobogrammatic pairs to both ends. For odd-length numbers, we start with each of the three symmetric strobogrammatic numbers (0, 1, 8) as the center and expand similarly. This strategy is efficient because it directly constructs valid numbers without needing to validate each candidate, significantly reducing the computational overhead compared to brute force methods.

This method is particularly effective because it leverages the recursive nature of strobogrammatic numbers. By building from the center, we ensure that each constructed number is valid by design, eliminating the need for post-construction validation. This recursive approach not only simplifies the problem but also ensures that all possible combinations are explored, guaranteeing the completeness of the solution set.

Step-by-step Algorithm

  1. Initialize the Base Cases: Start with two base conditions for recursion:

    • If n == 0, return a list containing an empty string because a number of length 0 is an empty string.
    • If n == 1, return a list containing the single-digit strobogrammatic numbers "0", "1", and "8".
  2. Recursive Construction: For values of n greater than 1, recursively build the strobogrammatic numbers by reducing n by 2 in each step. This reduction accounts for adding a pair of digits (one at the beginning and one at the end) to maintain the symmetry required for a number to be strobogrammatic.

  3. Building from the Middle: Use the results from the recursive call (which gives strobogrammatic numbers of length n-2) as the "middle part" around which the strobogrammatic pairs are added to form numbers of length n.

    • For n reduced to 2, start with the middle part as an empty string "", and for n reduced to 1, start with "0", "1", and "8".
  4. Adding Strobogrammatic Pairs: For each string obtained from the recursion:

    • If n is not equal to the original input (i.e., we are not at the first level of recursion), prepend and append "0" to the string (except at the outermost level to avoid leading zeros).
    • For all levels of recursion, prepend and append pairs "1" and "1", "6" and "9", "8" and "8", "9" and "6" to each of the strings obtained from the recursive call. This step ensures the strobogrammatic property is maintained.
  5. Collect Results: Combine all these strings to form the list of all possible strobogrammatic numbers of length n. Return this list as the result.

Algorithm Walkthrough

For n = 3, we aim to construct all possible strobogrammatic numbers of length 3 by building from the middle and expanding outwards, ensuring symmetry. Here's a detailed step-by-step walkthrough:

  1. Initial Call: The process begins by calling the method to construct strobogrammatic numbers of length 3.

  2. Recursive Construction:

    • Since n = 3 is not a base case, we proceed by reducing n by 2 and making a recursive call to construct strobogrammatic numbers of the reduced length (i.e., n = 1 in this step).
    • For n = 1, the base case directly returns the list ["0", "1", "8"].
  3. Backtracking and Building:

    • Starting with the results from the base case (["0", "1", "8"]), we backtrack and add pairs of digits to these single digits to build strobogrammatic numbers of length 3.
  4. Adding Pairs Around Each Base Case Result:

    • For "0" as the middle digit:
      • We add strobogrammatic pairs around "0", forming "101", "609", "808", and "906". Each pair is added such that the number remains symmetrical and strobogrammatic.
    • For "1" as the middle digit:
      • Similarly, we add pairs around "1", resulting in "111", "619", "818", and "916".
    • For "8" as the middle digit:
      • We add pairs around "8", forming "181", "689", "888", and "986".
  5. Combining Results:

    • All these newly formed numbers are then combined into a single list, which becomes the final output for n = 3.
    • Final Result: ["101", "609", "808", "906", "111", "619", "818", "916", "181", "689", "888", "986"].
  6. Backtracking to Complete:

    • Completion: At this point, we have constructed all strobogrammatic numbers of length 3 by effectively using backtracking. For each base case digit, we explored all possible symmetrical pairs that can surround it, ensuring the strobogrammatic property is maintained.
    • Return: The list of constructed numbers is returned as the output of the recursive process.

Code

Java
Saved to Cloud

. . . .

Complexity Analysis

  • Time Complexity: The time complexity is O(5^(n/2)) for generating all strobogrammatic numbers of length n. This is because, at each step (except the first and last for even and odd lengths, respectively), we have 5 choices (0 with 0, 1 with 1, 8 with 8, 6 with 9, and 9 with 6) for each of the n/2 positions (considering the symmetry of the numbers).

  • Space Complexity: The space complexity is also O(5^(n/2)) due to the storage requirements of the output. Additionally, the recursion stack adds another for the depth of the recursive calls, but this is overshadowed by the output space in most cases.

Strobogrammatic Number II (medium)
Maximum Length of Semi-Decreasing Subarrays (medium)
Mark as Completed

On this page

Problem Statement

Examples

Solution

Step-by-step Algorithm

Algorithm Walkthrough

Code

Complexity Analysis